package com.gitee.kamismile.gateway.component.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局filter-demo.
 *
 * @author zhaojun
 */
//@Component
public class VersionManagerGlobalFilter implements GlobalFilter {
  private final Logger logger = LoggerFactory.getLogger(getClass());

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    exchange.getAttributes().put("versionManager-start", System.currentTimeMillis());
    logger.info("这里是一个全局过滤器,你可以在这里修改请求上下文");
    return chain.filter(exchange).then(
            Mono.fromRunnable(() -> {
              Long startTime = exchange.getAttribute("versionManager-start");
              Long endTime=(System.currentTimeMillis() - startTime);
              if (startTime != null) {
                  logger.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
              }
            })
    );
  }
}
